/*
 * Copyright 2013-2014 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.sdgs.paas.sdk.core.log;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.event.HeartbeatEvent;
import org.springframework.cloud.client.discovery.event.HeartbeatMonitor;
import org.springframework.cloud.config.client.ConfigServerInstanceProvider;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;

/**
 * 初始化远程日志的configserver服务地址
 * <p>
 * 配置文件内使用${shtelpaas.log.uri}参数变量
 * <p>
 * 本初始化配置会访问注册中心获取实际可用的配置中心服务地址
 *
 * @author wjj
 *
 */
@Configuration
@EnableConfigurationProperties(PaasloggerProperties.class)
public class DiscoveryClientPaaslogBootstrapConfiguration {

	private static final Logger logger = LoggerFactory.getLogger(DiscoveryClientPaaslogBootstrapConfiguration.class);

	@Autowired
	private PaasloggerProperties config;
	@Autowired
	private ApplicationContext ctx;

	private HeartbeatMonitor monitor = new HeartbeatMonitor();

	@EventListener(ContextRefreshedEvent.class)
	public void startup(ContextRefreshedEvent event) {
		refresh();
	}

	@EventListener(HeartbeatEvent.class)
	public void heartbeat(HeartbeatEvent event) {
		if (monitor.update(event.getValue())) {
			refresh();
		}
	}

	private void refresh() {
		ConfigurableEnvironment env = (ConfigurableEnvironment) ctx.getEnvironment();
		String url = env.getProperty("shtelpaas.log.uri");
		if (url == null) {
			url = this.config.getUri();
			try {
				if (url == null) {
					String serviceId = this.config.getConfigserver();
					ServiceInstance server = ctx.getBean(ConfigServerInstanceProvider.class)
							.getConfigServerInstance(serviceId);
					url = server.getUri().toString();
					this.config.setUri(url);
				}

			} catch (Exception e) {
				url = "http://localhost:8050";
				logger.error("从注册中心获取配置中心地址失败!使用默认值：http://localhost:8050", e);
			}

			// CompositePropertySource composite = new
			// CompositePropertySource("shtelpaas.log.uri");
			Map<String, Object> source = new HashMap<>();
			source.put("shtelpaas.log.uri", url);
			// composite.addPropertySource(new
			// MapPropertySource("shtelpaas.log.uri", source));
			env.getPropertySources().addLast(new MapPropertySource("shtelpaas.log", source));
		}

	}

}
